# from info.models import User, News
from info.models import User, News, Category
from info.models import User
from . import index_bp
from info.utitls.response_code import RET
from flask import session, current_app, render_template, jsonify,request, g
from info.utitls.common import user_login_data
from info import redis_store
import logging
from info import constants
from info.models import User
"""
1, 参数获取
    cid,page, per_page
2,　参数校验
    非空判断
３，查询数据
   ３．１ 跟据ｃｉｄ的值获取，返回一个数据对象
   ３．２　根据返回的数据对象，分别提取相应的值
   ３．３　将返回的数据打包成为ｄａｔａ{}字典
４，返回数据

"""

@index_bp.route("/news_list")
def new_list():
    # 1 获取参数
    param_dict = request.args
    cid = param_dict.get("cid")
    page = param_dict.get("page", 1)
    per_page = param_dict.get("per_page", 10)
    # 2,非空判断
    if not cid:
        current_app.logger.error("参数不足")
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")
    # 2.2 数据格式是否转化成为ｉｎｔ类型
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数格式错误")
    # 3.1 分页的方式ｐａｇｉｎｔａｔｅ查询新闻列表的数据
    filter_list = []
    if cid != 1:
        filter_list.append(News.category_id == cid)

    try:
        paginate = News.query.filter(*filter_list).order_by(News.create_time.desc()) \
                .paginate(page, per_page, False)
        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询新闻对象列表异常")
    # 3.2 将新闻对象列表转换成为新闻字典列表
    news_dict_list = []
    for news in news_list if news_list else []:
        news_dict_list.append(news.to_dict())
    data = {
        "newsList": news_dict_list,
        "current_page": current_page,
        "total_page":total_page

    }
    return jsonify(errno=RET.OK, errmsg="新闻列表数据查询成功", data=data)


# 2.使用蓝图,这是显示页面登录后的页面
@index_bp.route("/")
@user_login_data
def index():
    # ----------数据查询及展示-----------
    user = g.user
            # if user:
            #         user_dict = user.to_dict()

    # ------------2.查询新闻信息点击量---------------
    try:
        # 获取点击量排行茜六的新闻对象
        news_rank_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询新闻数据异常")
    """
    先循环news_rank_list这个列表对象，
    for news_obj in news_rank_list:
        将每一个字典对象转化成为字典
        news_dict = news_obj.to_dict()
        将每个字典添加到字典列表中
        new_dict_list.append(new_dict)
    """
    news_dict_list = []

    # 循环news_rank_list，如果news_rank_lis存在的话，
    for news_obj in news_rank_list if news_rank_list else []:
        news_dict = news_obj.to_dict()
        news_dict_list.append(news_dict)
#  -------------3查询数据fen类--------------
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询分类数据异常")
    categories_dict_list = []
    for category in categories if categories else []:
        category_dict = category.to_dict()
        categories_dict_list.append(category_dict)



    # 首页数据字典
    data = {
            "user_info": user.to_dict() if user else None,
            "news_rank_list": news_dict_list,
            "categories": categories_dict_list

    }

    return render_template("news/index.html", data=data)


@index_bp.route("/favicon.ico")
def get_favicon():
    """获取网站图标"""

    """
    Function used internally to send static files from the static
        folder to the browser
    内部用来发送静态文件到浏览器的方法
    """
    return current_app.send_static_file("news/favicon.ico")


















